﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using justice.Models;

namespace justice.Controllers
{
    [Authorize]
    public class JudiciaryController : Controller
    {
        // GET: Judiciary   司法局
        justiceEntities dal = new justiceEntities();
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.JudiciaryList = dal.judiciary.ToList();
            return View();
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ActionResult AddJudiciaryView()
        {
            return View();
        }
        public ActionResult AddJudiciary(judiciary judiciary)
        {
            dal.judiciary.Add(judiciary);
            if (dal.SaveChanges() > 0)
            {
                return RedirectToAction("Index", "Judiciary");
            }
            return View("AddJudiciaryView");
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult ModJudiciaryView(int id)
        {
            judiciary jud = dal.judiciary.ToList().Find(l => l.id == id);
            return View(jud);
        }
        public ActionResult ModJudiciary(judiciary judiciary)
        {
            judiciary jud = dal.judiciary.ToList().Find(l => l.id == judiciary.id);
            jud.judiciaryName = judiciary.judiciaryName;
            jud.phone = judiciary.phone;
            jud.readdress = judiciary.readdress;
            jud.abbreviation = judiciary.abbreviation;
            if (dal.SaveChanges() > 0)
            {
                return RedirectToAction("Index", "Judiciary");
            }
            return View("ModJudiciaryView");
        }
        public JsonResult DelJudiciary(int id)
        {
            judiciary jud = dal.judiciary.ToList().Find(l => l.id == id);
            if(jud != null)
            {
                //此处一系列处理  外键关系
                List<justice_user> justice_user_list = dal.justice_user.ToList().FindAll(l => l.unit_id == id);//查次机构下所有用户
                foreach (var item in justice_user_list)//查用户所有受理鉴定单
                {
                    List<Shroff_book> shroff_book_list = dal.Shroff_book.ToList().FindAll(l => l.enter_user_id == item.id);
                    if (shroff_book_list.Count > 0)
                    {
                        return Json("false");
                    }
                }
                //无外键关系  直接删除
                dal.judiciary.Remove(jud);
            }
            if (dal.SaveChanges() > 0)
                return Json("true");
            else
                return Json("false");
        }
    }
}